/**
 * 统一接口 loading 处理
 * 采用 vue-wait
 * vue-wait 会默认取用接口的 key 作为 loader
 */
import axios from 'axios';
import wait from '../../../plugins/vue-wait';

const waitPool = {};

/**
 * 处理 loading 开始和结束
 *
 * @param {*} config
 * @param {*} type
 */
function handleLoading(config, type) {
  const handleDefaultLoading = config.handleDefaultLoading;
  const loader = typeof handleDefaultLoading === 'string' ? handleDefaultLoading : config._apiKey;

  if (type === 'start') {
    waitPool[loader] = waitPool[loader] || 0;
    waitPool[loader]++;

    wait.start(loader);
  } else if (type === 'end') {
    if (waitPool[loader] > 0) {
      waitPool[loader]--;
    }

    if (waitPool[loader] === 0) {
      // 延时 500ms 关闭，防重复点击
      setTimeout(() => {
        waitPool[loader] === 0 && wait.end(loader);
      }, 500);
    }
  }
}

export default instance => {
  // Add a request interceptor
  instance.interceptors.request.use(
    config => {
      if (config.handleDefaultLoading !== false) {
        handleLoading(config, 'start');
      }

      return config;
    },
    error => {
      // Do something with request error
      if (error.config.handleDefaultLoading !== false) {
        handleLoading(error.config, 'end');
      }
      return Promise.reject(error);
    }
  );

  // Add a response interceptor
  instance.interceptors.response.use(
    response => {
      if (response.config.handleDefaultLoading !== false) {
        handleLoading(response.config, 'end');
      }
      return response;
    },
    error => {
      const config = error && error.config && error.config;
      if (config && config.handleDefaultLoading !== false) {
        handleLoading(config, 'end');
      }

      // 重复请求读取 message
      if (axios.isCancel(error)) {
        handleLoading(error.message, 'end');
      }

      return Promise.reject(error);
    }
  );
};
